<!DOCTYPE html>
<html>
<head>
    <title>楼层数据统计表</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .floor {
            background-color: #e0e0e0;
            font-weight: bold;
        }
        .selected {
            background-color: #4CAF50;
            color: white;
        }
        .disabled {
            background-color: #9e9e9e;
            color: #e0e0e0;
            text-decoration: line-through;
        }
        .header {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            text-align: center;
            font-size: 18px;
            margin-bottom: 10px;
        }
        .legend {
            margin-top: 10px;
            display: flex;
            gap: 20px;
        }
        .legend-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .legend-color {
            width: 20px;
            height: 20px;
        }
        .selected-legend {
            background-color: #4CAF50;
        }
        .unselected-legend {
            background-color: #fff;
            border: 1px solid #ddd;
        }
        .disabled-legend {
            background-color: #9e9e9e;
        }
        .progress-container {
            margin-top: 10px;
            width: 100%;
            background-color: #f1f1f1;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .progress-bar {
            height: 20px;
            background-color: #4CAF50;
            border-radius: 5px;
            width: 0%;
            text-align: center;
            line-height: 20px;
            color: white;
            font-weight: bold;
            transition: width 0.3s;
        }
        .settings-container {
            margin-bottom: 15px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .settings-row {
            display: flex;
            gap: 15px;
            margin-bottom: 10px;
        }
        .settings-field {
            flex: 1;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .blue-button {
            background-color: #2196F3;
        }
        .blue-button:hover {
            background-color: #0b7dda;
        }
        .orange-button {
            background-color: #ff9800;
        }
        .orange-button:hover {
            background-color: #e68a00;
        }
        .help-text {
            font-size: 0.8em;
            color: #666;
            margin-top: 4px;
        }
        .export-container {
            margin-top: 15px;
        }
        #exportResult {
            margin-top: 10px;
            padding: 8px;
            border: 1px solid #ddd;
            display: none;
            min-height: 60px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="header">楼层数据统计表</div>
    
    <div class="settings-container">
        <div class="settings-row">
            <div class="settings-field">
                <label for="buildingTitle">楼栋名称:</label>
                <input type="text" id="buildingTitle" value="楼层数据统计表">
                <div class="help-text">设置楼栋名称（如"1栋"、"A栋"等）</div>
            </div>
        </div>
        
        <div class="settings-row">
            <div class="settings-field">
                <label for="floorCount">楼层总数:</label>
                <input type="number" id="floorCount" min="1" max="100" value="30">
                <div class="help-text">设置建筑的总楼层数（1-100之间）</div>
            </div>
            <div class="settings-field">
                <label for="unitsPerFloor">每层户数:</label>
                <input type="number" id="unitsPerFloor" min="1" max="20" value="6">
                <div class="help-text">设置每层的户数（1-20之间）</div>
            </div>
        </div>
        
        <div class="settings-row">
            <div class="settings-field">
                <label for="initialDataInput">已统计房号:</label>
                <textarea id="initialDataInput" rows="3" placeholder="示例: 101,203,302,405 或 1-101,2-203,3-305"></textarea>
                <div class="help-text">输入已统计房号，用逗号分隔</div>
            </div>
            <div class="settings-field">
                <label for="disabledRoomsInput">禁用房号:</label>
                <textarea id="disabledRoomsInput" rows="3" placeholder="示例: 101,203,302,405 或 1-101,2-203,3-305"></textarea>
                <div class="help-text">输入需要禁用的房号（不参与统计），用逗号分隔</div>
            </div>
        </div>
        
        <button id="generateBtn" class="orange-button">生成表格</button>
    </div>
    
    <div class="progress-container">
        <div id="progressBar" class="progress-bar" style="width: 0%">0%</div>
    </div>
    
    <table id="buildingTable">
        <thead id="tableHead">
            <tr>
                <th>楼层</th>
                <!-- Header will be generated dynamically -->
            </tr>
        </thead>
        <tbody id="tableBody">
            <!-- Table content will be generated by JavaScript -->
        </tbody>
    </table>
    
    <div class="legend">
        <div class="legend-item">
            <div class="legend-color selected-legend"></div>
            <span>已统计</span>
            <span id="countSelected" style="margin-left: 5px; font-weight: bold;">(0)</span>
        </div>
        <div class="legend-item">
            <div class="legend-color unselected-legend"></div>
            <span>未统计</span>
            <span id="countUnselected" style="margin-left: 5px; font-weight: bold;">(0)</span>
        </div>
        <div class="legend-item">
            <div class="legend-color disabled-legend"></div>
            <span>已禁用</span>
            <span id="countDisabled" style="margin-left: 5px; font-weight: bold;">(0)</span>
        </div>
        <div class="export-container" style="margin-left: auto;">
            <button id="exportBtn" class="blue-button">导出已统计房号</button>
            <div id="exportResult"></div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // DOM elements
            const tableHead = document.getElementById('tableHead');
            const tableBody = document.getElementById('tableBody');
            const initialDataInput = document.getElementById('initialDataInput');
            const disabledRoomsInput = document.getElementById('disabledRoomsInput');
            const floorCountInput = document.getElementById('floorCount');
            const unitsPerFloorInput = document.getElementById('unitsPerFloor');
            const generateBtn = document.getElementById('generateBtn');
            const exportBtn = document.getElementById('exportBtn');
            const exportResult = document.getElementById('exportResult');
            const countSelected = document.getElementById('countSelected');
            const countUnselected = document.getElementById('countUnselected');
            const countDisabled = document.getElementById('countDisabled');
            const progressBar = document.getElementById('progressBar');
            const headerDiv = document.querySelector('.header');
            
            // Initial values
            let buildingTitle = document.getElementById('buildingTitle').value || '楼层数据统计表';
            let floorCount = parseInt(floorCountInput.value) || 30;
            let unitsPerFloor = parseInt(unitsPerFloorInput.value) || 6;
            let initialData = [];
            let disabledRooms = [];
            let totalRooms = floorCount * unitsPerFloor;
            
            // Function to update counters and progress
            function updateCounters() {
                const selectedCount = document.querySelectorAll('td.selected:not(.floor)').length;
                const disabledCount = document.querySelectorAll('td.disabled:not(.floor)').length;
                const countableRooms = totalRooms - disabledCount;
                const unselectedCount = countableRooms - selectedCount;
                const percentage = countableRooms > 0 ? Math.round((selectedCount / countableRooms) * 100) : 0;
                
                // Update counters
                countSelected.textContent = `(${selectedCount})`;
                countUnselected.textContent = `(${unselectedCount})`;
                countDisabled.textContent = `(${disabledCount})`;
                
                // Update progress bar
                progressBar.style.width = `${percentage}%`;
                progressBar.textContent = `${percentage}%`;
                
                // Update header
                headerDiv.textContent = `${buildingTitle} (${floorCount}层楼，每层${unitsPerFloor}户) - 完成进度: ${percentage}%`;
            }
            
            // Function to generate table headers
            function generateTableHeaders() {
                const headerRow = tableHead.querySelector('tr');
                headerRow.innerHTML = '<th>楼层</th>';
                
                for (let unit = 1; unit <= unitsPerFloor; unit++) {
                    const unitHeader = document.createElement('th');
                    unitHeader.textContent = String(unit).padStart(2, '0');
                    headerRow.appendChild(unitHeader);
                }
            }
            
            // Function to render the table
            function renderTable() {
                // Parse initial data and disabled rooms
                initialData = parseInputData(initialDataInput.value);
                disabledRooms = parseInputData(disabledRoomsInput.value);
                
                // Update total rooms
                totalRooms = floorCount * unitsPerFloor;
                
                // Generate table headers
                generateTableHeaders();
                
                // Clear existing table body
                tableBody.innerHTML = '';
                
                // Function to check room status
                function checkRoomStatus(floor, unit) {
                    const roomNumber = `${floor}${String(unit).padStart(2, '0')}`;
                    
                    // Check if room is disabled first
                    if (isRoomInList(roomNumber, disabledRooms)) {
                        return 'disabled';
                    }
                    
                    // Check if room is selected
                    if (isRoomInList(roomNumber, initialData)) {
                        return 'selected';
                    }
                    
                    // Room is normal
                    return 'normal';
                }
                
                // Generate floors (from top to bottom)
                for (let floor = floorCount; floor >= 1; floor--) {
                    const row = document.createElement('tr');
                    
                    // Add floor number cell
                    const floorCell = document.createElement('td');
                    floorCell.textContent = floor;
                    floorCell.classList.add('floor');
                    row.appendChild(floorCell);
                    
                    // Add units per floor
                    for (let unit = 1; unit <= unitsPerFloor; unit++) {
                        const cell = document.createElement('td');
                        const unitNum = String(unit).padStart(2, '0');
                        cell.textContent = `${floor}${unitNum}`;
                        
                        // Set initial status
                        const status = checkRoomStatus(floor, unit);
                        if (status === 'selected') {
                            cell.classList.add('selected');
                        } else if (status === 'disabled') {
                            cell.classList.add('disabled');
                        }
                        
                        // Add click event to toggle selection (but not for disabled rooms)
                        cell.addEventListener('click', function() {
                            // Don't allow selection of disabled rooms
                            if (this.classList.contains('disabled')) {
                                return;
                            }
                            
                            // Toggle selection
                            this.classList.toggle('selected');
                            updateCounters();
                        });
                        
                        // Add right-click event to toggle disabled status
                        cell.addEventListener('contextmenu', function(e) {
                            e.preventDefault(); // Prevent the browser context menu
                            
                            // Can't disable a room that's already selected
                            if (this.classList.contains('selected')) {
                                this.classList.remove('selected');
                            }
                            
                            // Toggle disabled status
                            this.classList.toggle('disabled');
                            updateCounters();
                        });
                        
                        row.appendChild(cell);
                    }
                    
                    tableBody.appendChild(row);
                }
                
                // Update counters after rendering
                updateCounters();
            }
            
            // Function to parse input data (handles both formats)
            function parseInputData(inputValue) {
                if (!inputValue || inputValue.trim() === '') {
                    return [];
                }
                
                return inputValue.trim().split(/[,\s]+/).filter(item => item.length > 0);
            }
            
            // Function to check if a room is in a list
            function isRoomInList(roomNumber, roomList) {
                // Direct match
                if (roomList.includes(roomNumber)) {
                    return true;
                }
                
                // Check for prefix format (e.g., 1-101)
                for (const item of roomList) {
                    if (item.includes('-')) {
                        const parts = item.split('-');
                        if (parts.length === 2 && parts[1] === roomNumber) {
                            return true;
                        }
                    }
                }
                
                return false;
            }
            
            // Function to export selected rooms
            function exportSelectedRooms() {
                const selectedRooms = [];
                const rows = tableBody.querySelectorAll('tr');
                
                rows.forEach(row => {
                    const floorCell = row.querySelector('td.floor');
                    if (floorCell) {
                        const cells = row.querySelectorAll('td:not(.floor)');
                        
                        cells.forEach(cell => {
                            if (cell.classList.contains('selected')) {
                                selectedRooms.push(cell.textContent);
                            }
                        });
                    }
                });
                
                return selectedRooms;
            }
            
            // Generate button handler
            generateBtn.addEventListener('click', function() {
                // Get values from inputs
                buildingTitle = document.getElementById('buildingTitle').value || '楼层数据统计表';
                floorCount = parseInt(floorCountInput.value) || 30;
                unitsPerFloor = parseInt(unitsPerFloorInput.value) || 6;
                
                // Validate inputs
                floorCount = Math.min(Math.max(floorCount, 1), 100);
                unitsPerFloor = Math.min(Math.max(unitsPerFloor, 1), 20);
                
                // Update input values
                floorCountInput.value = floorCount;
                unitsPerFloorInput.value = unitsPerFloor;
                
                // Render the table
                renderTable();
            });
            
            // Export button handler
            exportBtn.addEventListener('click', function() {
                const selectedRooms = exportSelectedRooms();
                exportResult.style.display = 'block';
                
                if (selectedRooms.length > 0) {
                    const disabledCount = document.querySelectorAll('td.disabled:not(.floor)').length;
                    const countableRooms = totalRooms - disabledCount;
                    const percentage = countableRooms > 0 ? Math.round((selectedRooms.length / countableRooms) * 100) : 0;
                    
                    exportResult.innerHTML = `
                        <div>已统计: <strong>${selectedRooms.length}</strong> 户 (${percentage}%)</div>
                        <div style="margin-top: 5px;">${selectedRooms.join(', ')}</div>
                    `;
                } else {
                    exportResult.innerHTML = '<div>暂无已统计房号</div>';
                }
            });
            
            // Initial render with default values
            renderTable();
            
            // Add info about right-click functionality
            const helpText = document.createElement('div');
            helpText.innerHTML = '<div style="margin-top: 15px; font-style: italic; color: #666;">提示: 单击房间切换"已统计"状态，右键单击房间切换"禁用"状态</div>';
            document.querySelector('.legend').after(helpText);
        });
    </script>
</body>
</html>